package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.HmDevice;
import com.example.demo.mapper.DeviceMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/device")
public class DeviceController extends BaseController {

    @Resource
    DeviceMapper deviceMapper;
    @PostMapping
    public Result<?> save(@RequestBody HmDevice hmDevice) {
        deviceMapper.insert(hmDevice);
        return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody HmDevice hmDevice) {
        deviceMapper.updateById(hmDevice);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Integer id) {
        deviceMapper.deleteById(id);
        return Result.success();
    }

    /*@GetMapping("/{id}")
    public Result<?> getById(@PathVariable Integer id) {
        return Result.success(deviceMapper.selectById(id));
    }*/

    @GetMapping("/{companyName}")
    public Result<?> getByCompanyName(@PathVariable String companyName) {
        LambdaQueryWrapper<HmDevice> wrapper = Wrappers.<HmDevice>lambdaQuery();
        if (StrUtil.isNotBlank(companyName)) {
            wrapper.like(HmDevice::getCompanyName, companyName);
        }

        return Result.success(deviceMapper.selectList(wrapper));
    }

    /**
     *
     * @author fqc
     * @date 2023/11/23 17:43
     * @param pageNum
     * @param pageSize
     * @param companyName
     * @param device
     * @return com.example.demo.common.Result<?>
     */
    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String companyName,
                              @RequestParam(defaultValue = "") String device) {
        LambdaQueryWrapper<HmDevice> wrapper = Wrappers.<HmDevice>lambdaQuery();
        if (StrUtil.isNotBlank(companyName)) {
            wrapper.like(HmDevice::getCompanyName, companyName);
        }
        if (StrUtil.isNotBlank(device)) {
            wrapper.like(HmDevice::getDevice, device);
        }

        Page<HmDevice> devicePage = deviceMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(devicePage);
    }

}
